#include <iostream>
#include <string>
#include <pthread.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t _m;
pthread_cond_t _c;

int wait_num = 0; // 在条件变量中等待的线程个数

void *print(void *name)
{
    string s = (const char *)name;
    while (true)
    {
        pthread_mutex_lock(&_m);
        while(wait_num != 0) // 在条件变量中等待的线程个数如果不为0
        {
            pthread_cond_signal(&_c);
            wait_num--;
        }
        cout << "我是" << s << endl;
        wait_num++;
        pthread_cond_wait(&_c, &_m);

        sleep(1);

        pthread_mutex_unlock(&_m);
    }
}

int main()
{
    pthread_t ta = 0;
    pthread_t tb = 0;
    pthread_mutex_init(&_m, nullptr);
    pthread_cond_init(&_c, nullptr);

    pthread_create(&ta, nullptr, print, (void *)"线程A");
    pthread_create(&tb, nullptr, print, (void *)"线程B");

    pthread_join(ta, nullptr);
    pthread_join(tb, nullptr);
    return 0;
}